package com.yf.modules.security.service;

import com.yf.modules.security.model.dto.JwtUserDto;
import com.yf.modules.security.service.api.AuthService;
import com.yf.modules.security.model.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author chentianwei
 * @date 2023/5/4 15:01
 * @description 重写用户信息服务
 */
@Service(value = "userDetailsService")
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    private final  AuthService authService;

    public UserDetailsServiceImpl(AuthService authService) {
        this.authService = authService;
    }


    @Override
    public JwtUserDto loadUserByUsername(String username) throws UsernameNotFoundException {

        //TODO:1.先从缓存中获取

        //2.如没有再从数据库获取，找不到抛出异常
        UserDto user = authService.findByUserName(username);
        if (Objects.isNull(user)){
            throw new UsernameNotFoundException(username);
        }
        //TODO:不允许传空值
        return new JwtUserDto(user, null, null);
    }
}
